package com.module.lemlin.owner

import android.app.Application
import androidx.lifecycle.*
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.http.*
import io.reactivex.rxjava3.disposables.CompositeDisposable
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.whileSelect
import java.lang.Exception

abstract class OwnerViewModel(application: Application) : AndroidViewModel(application) {

    /**
     * 设置http正确码
     * */
    abstract val httpCodeProPer: Int

    /**
     * token过期/401错误时调用
     * */
    abstract fun onTokenOverdue()


    val dispose: CompositeDisposable = CompositeDisposable()

    public override fun onCleared() {
        if (dispose.size() > 0 && !dispose.isDisposed) {
            dispose.dispose()
        }
    }

    fun <data : HttpResponseData> setRxLifeScope(
        listener: SubscribeViewModel<data>, block: suspend CoroutineScope.() -> data?
    ) = rxLifeScope.launch({
        val data = block() ?: throw CustomException(
            "9999", "总参数为NULL"
        )
        if (data.code != httpCodeProPer) throw CustomException(
            data.code.toString(), data.message
        )
        listener.onSuccess(data)
    }, {
        if (it.code == 401) {
            onTokenOverdue()
        }
        listener.onFailure(it)
    }, {
        listener.onStart()
    })

    fun <data> setViewModelScope(
        listener: SubscribeViewModel<data>, block: suspend CoroutineScope.() -> data
    ) = viewModelScope.launch {
        listener.onStart()
        try {
            listener.onSuccess(block())
        } catch (e: Throwable) {
            listener.onFailure(e)
        }
    }
}
